package org.crmsystem.controller;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.crmsystem.model.*;
import org.crmsystem.service.IHandleLogService;
import org.crmsystem.service.IOrgService;
import org.crmsystem.service.IProductService;
import org.crmsystem.service.IStaffService;
import org.crmsystem.util.DateUtil;
import org.crmsystem.util.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.ParseException;
import java.util.*;

/**
 * Created by yujiagan
 */


@Controller
@RequestMapping("/handlelog")
public class HandleLogController {
    private static  Logger logger = LogManager.getLogger(HandleLogController.class);
    @Autowired
    private IHandleLogService handleLogService;
    @Autowired
    private IOrgService orgService;
    @Autowired
    private IStaffService staffService;
    @Autowired
    private IProductService productService;

    /**
     * 定向到添加日志页面
     */
    @RequestMapping("/addlog")
    public ModelAndView getIndex(){
        return getLists("handleLog");
    }
    /**
     * 查询所有机构
     * @param
     * @return
     */
    @RequestMapping("/searchorg")
    @ResponseBody
    public List<OrgInfo> getOrg(){
        HashMap<String,Object> map = new HashMap<String,Object>();
        map.put("search","name");
        map.put("searchText","");
        List<OrgInfo> list = orgService.selectOrgList(map);
        return list;
    }

    /**
     * 精确查询机构，带出机构信息
     * @param morgId
     * @return
     */
    @RequestMapping("/searchorgname")
    @ResponseBody
    public OrgInfo getOrgById(String morgId){
        int orgId = Integer.parseInt(morgId);
        OrgInfo orgInfo = orgService.getOrgById(orgId);
        return orgInfo;
    }

    /**
     * 模糊查询员工
     * @return
     */
    @RequestMapping("/searchstaff")
    @ResponseBody
    public List<Object> getStaffByName(){
        Staff staff = new Staff();
        Map map = new HashMap<>();
        map.put("staff",staff);
        map.put("pageSize",100);
        map.put("currPage",1);
        Page page=staffService.getStaff(map);
       List<Object> slist=page.getResult();
        return slist;
    }

    /**
     * 精确查询员工信息
     *
     * @return
     */
    @RequestMapping("/getstaff")
    @ResponseBody
    public List<Object> getStaffByRealName(String operId){
        int id = Integer.parseInt(operId);
        Staff staff = new Staff();
        staff.setId(id);
        Map map = new HashMap<>();
        map.put("staff",staff);
        map.put("pageSize",0);
        map.put("currPage",0);
        Page page=staffService.getStaff(map);
        List<Object> rlist =page.getResult();
        return rlist;
    }

    /**
     * 添加操作日志
     * @param handleLog
     * @param morgKindId
     * @param mcontactId
     * @param datestring
     * @param moperatorId
     * @param mownerId
     * @param mlevelId
     * @param morgId
     * @return
     * @throws Exception
     */
    @RequestMapping("/inserthandlelog")
    public String addHandleLog(HandleLog handleLog,String mproId,String morgKindId,String mcontactId,String datestring,String moperatorId,String mownerId,String mlevelId, String morgId) throws Exception{
        int proId = Integer.parseInt(mproId);
        int operatorId = Integer.parseInt(moperatorId);
        int ownerId = Integer.parseInt(mownerId);
        int levelId = Integer.parseInt(mlevelId);
        int orgId = Integer.parseInt(morgId);
        int contactId = Integer.parseInt(mcontactId);
        int orgKindId = Integer.parseInt(morgKindId);
        if(datestring==null ||datestring.equals("")){
            datestring=DateUtil.formatDate(new Date(),"yyyy-MM-dd");
        }
        Date logdate = DateUtil.formatDate(datestring,"yyyy-MM-dd");
        handleLog.setProId(proId);
        handleLog.setLogDate(logdate);
        handleLog.setOrgId(orgId);
        handleLog.setOrgKindId(orgKindId);
        handleLog.setOperatorId(operatorId);
        handleLog.setOwnerId(ownerId);
        handleLog.setLevelId(levelId);
        handleLog.setContactId(contactId);
        int flag = handleLogService.insertHandleLog(handleLog);
        return "redirect:/handlelog/alllogs";
    }

    /**
     * 查询所有日志列表
     * @return
     */
    @RequestMapping("/alllogs")

    public ModelAndView getAllLogs(Integer currpage,Integer pagesize){
        return new ModelAndView("logList");
    }

    @RequestMapping("/getlogs")
    @ResponseBody
    public List<HandleLog> getLogs(String type,String keyword,Integer currpage,Integer pagesize,String startdate,String enddate){
        List<HandleLog> alist = new ArrayList<HandleLog>();
        Map<String,Object> map = new HashMap<String,Object>();
            if(currpage==null){
            currpage=1;
            }
        if("".equals(startdate)){
            startdate=null;
        }
        if("".equals(enddate)){
            enddate=null;
        }
        map.put("type",type);
        map.put("keyword",keyword);
        map.put("currPage",currpage);
        map.put("pageSize",pagesize);
        map.put("startdate",startdate);
        map.put("enddate",enddate);
        alist = handleLogService.getHandleLogByKeyword(map);
        for (HandleLog h: alist) {
            h.setDatostr(DateUtil.formatDate(h.getLogDate(),"yyyy-MM-dd"));
        }
        return alist;
    }

    /**
     * 删除日志
     * @param id
     * @return
     */
    @RequestMapping("/dellog")
    public String deleteHandleLog(String id){
        int hid = Integer.parseInt(id);
         handleLogService.deleteHandleLog(hid);
        return "redirect:/handlelog/alllogs";

    }

    /**
     * 根据id获取要更改日志的信息
     * @param id
     * @return
     */
    @RequestMapping("/updatelog")
    public ModelAndView updateLog(String id){
        int flag = Integer.parseInt(id);
        HandleLog handlelog = handleLogService.getHandleLogById(flag);
        handlelog.setDatostr(DateUtil.formatDate(handlelog.getLogDate(),"yyyy-MM-dd"));
        Map<String,Object> map = new HashMap<String,Object>();
        ModelAndView m = getLists("handleLog");
        m.addObject("hl",handlelog);
        return m;
    }

    /**
     * 修改日志
     * @param handleLog
     * @param lid
     * @param morgKindId
     * @param mcontactId
     * @param datestring
     * @param moperatorId
     * @param mownerId
     * @param mlevelId
     * @param morgId
     * @return
     * @throws Exception
     */
    @RequestMapping("/updatehandlelog")
    public String updatehandlelog(HandleLog handleLog,String lid,String morgKindId,String mcontactId,String datestring,String moperatorId,String mownerId,String mlevelId, String morgId) throws Exception{
        int id= Integer.parseInt(lid);
        int operatorId = Integer.parseInt(moperatorId);
        int ownerId = Integer.parseInt(mownerId);
        int levelId = Integer.parseInt(mlevelId);
        int orgId = Integer.parseInt(morgId);
        int contactId = Integer.parseInt(mcontactId);
        int orgKindId = Integer.parseInt(morgKindId);
        Date logdate = DateUtil.formatDate(datestring,"yyyy-MM-dd");
        handleLog.setProId(1);
        handleLog.setId(id);
        handleLog.setLogDate(logdate);
        handleLog.setOrgId(orgId);
        handleLog.setOrgKindId(orgKindId);
        handleLog.setOperatorId(operatorId);
        handleLog.setOwnerId(ownerId);
        handleLog.setLevelId(levelId);
        handleLog.setContactId(contactId);
        int flag = handleLogService.updateHandleLog(handleLog);
        return "redirect:/handlelog/alllogs";
    }

    /**
     * 查询所有产品信息
     * @return
     */
    @RequestMapping("/getproduct")
    @ResponseBody
    public List<Product> getAllProduct(){
        List<Product> plist = productService.select();
        return plist;
    }

    /**
     * 根据产品id查询产品
     * @param proId
     * @return
     */
    @RequestMapping("/getrelproduct")
    @ResponseBody
    public Product getrelProduct(String proId){
        int id = Integer.parseInt(proId);
        Product pro = productService.selectByPrimaryKey(id);
        return pro;
    }


    /**
     * 查看日志详情
     * @param id 日志编号
     * @return
     */
    @RequestMapping("/logdetails")
    public ModelAndView getLog(String id){
        int lid = Integer.parseInt(id);
        HandleLog h2 = handleLogService.getHandleLogById(lid);
        h2.setDatostr(DateUtil.formatDate(h2.getLogDate(),"yyyy-MM-dd"));
        Map map = new HashMap<>();
        map.put("h2",h2);
        return new ModelAndView("logDetails",map);
    }

    /**
     *员工、机构、产品返回到新增或修改页面
     * @param pathstr
     * @return
     */
    public ModelAndView getLists(String pathstr) {
        List<Product> plist = productService.select();

        List<OrgInfo> olist = orgService.selectOrgList(null);
        Staff staff = new Staff();
        Map smap = new HashMap<>();
        smap.put("staff", staff);
        smap.put("pageSize", 100);
        smap.put("currPage", 1);
        Page page=staffService.getStaff(smap);
        List<Object> slist = page.getResult();
        Map map = new HashMap<>();
        ModelAndView m = new ModelAndView(pathstr);
        m.addObject("plist", plist);
        m.addObject("olist", olist);
        m.addObject("slist", slist);
        return m;
    }


    /**
     * 导出到EXCEL
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/exportexcel")
    public String outExcle(HttpServletRequest request, HttpServletResponse response,String startdate,String enddate,String type,String keyword){
        String fileName = "操作日志记录";
        List<HandleLog> projects = outData(startdate,enddate,type,keyword);
        List<Map<String, Object>> list = outExcelRecord(projects);
        String columnNames[] = { "编号", "机构名称", "机构级别", "日志所属人", "联系人", "负责人", "日志日期","日志等级"};
        String keys[] = { "id", "orgName", "orgKindName", "ownerName", "contactName", "operName", "logdate","levelName"};
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ExcelUtil.createWorkBook(list, keys, columnNames).write(os);
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] content = os.toByteArray();
        InputStream is = new ByteArrayInputStream(content);
        response.reset();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        try {
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(out);
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (final IOException e) {
            try {
                throw e;
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        } finally {
            if (bis != null)
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if (bos != null)
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }

        return null;
    }
    /**
     * 导出Excel时获取所有信息
     *
     * @return
     */
    private List<HandleLog> outData(String startdate,String enddate,String type,String keyword){
        // TODO Auto-generated method stub
        List<Map<String, Object>> list = null;
        List<HandleLog> alist = new ArrayList<HandleLog>();
        Map<String,Object> map = new HashMap<String,Object>();
        if("".equals(startdate)){
            startdate=null;
        }
        if("".equals(enddate)){
            enddate=null;
        }
        map.put("type",type);
        map.put("keyword",keyword);
        map.put("startdate",startdate);
        map.put("enddate",enddate);
        alist = handleLogService.getHandleLogByKeyword(map);
        for (HandleLog h: alist) {
            h.setDatostr(DateUtil.formatDate(h.getLogDate(),"yyyy-MM-dd"));
        }
        return alist;
    }
    /**
     * 记录要导出的所有信息
     *
     * @param projects
     * @return
     */
    private List<Map<String, Object>> outExcelRecord(List<HandleLog> projects){
        List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("sheetName", "sheet1");
        listmap.add(map);
        HandleLog handleLog = null;
        for (int j = 0; j < projects.size(); j++) {
            handleLog = projects.get(j);
            Map<String, Object> mapValue = new HashMap<String, Object>();
            mapValue.put("id", handleLog.getId());
            mapValue.put("orgName", handleLog.getOrgName());
            mapValue.put("orgKindName", handleLog.getOrgKindName());
            mapValue.put("ownerName", handleLog.getOwnerName());
            mapValue.put("contactName", handleLog.getContactName());
            mapValue.put("operName", handleLog.getOperName());
            mapValue.put("logdate", handleLog.getDatostr());
            mapValue.put("levelName", handleLog.getLevelName());
            listmap.add(mapValue);
        }
        return listmap;
    }


    @RequestMapping("/gettotalinfo")
    @ResponseBody
    public Map<String,Object> getTotalInfo(String type,String keyword,Integer pagesize,String startdate,String enddate){
        Map<String,Object> map = new HashMap<String,Object>();
        if("".equals(startdate)){
            startdate=null;
        }
        if("".equals(enddate)){
            enddate=null;
        }
        map.put("type",type);
        map.put("keyword",keyword);
        map.put("startdate",startdate);
        map.put("enddate",enddate);

        int totalData = handleLogService.getLogCount(map);
        int totalPage ;
        if(totalData%pagesize==0){
            totalPage=totalData/pagesize;
        }else{
            totalPage=totalData/pagesize+1;
        }

        Map<String,Object> datamap = new HashMap<String,Object>();
        datamap.put("totalData",totalData);
        datamap.put("totalPage",totalPage);
        return datamap;
    }

}
